/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Diagrama.java
 *
 * Created on Jul 11, 2012, 3:45:26 AM
 */
package sistemadeproyectos;

import java.util.Calendar;
import java.util.Date;
import java.sql.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public class Diagrama extends ApplicationFrame {

    static String equipo;
    /** Creates new form Diagrama */
    public Diagrama(String title, String equipo) {
       
        super(title);
        this.equipo = equipo;
        final IntervalCategoryDataset dataset = createDataset();
        final JFreeChart pizarra = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(pizarra);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 350));
        setContentPane(chartPanel);
        initComponents();
        this.setVisible(true);
    }
    
    public static IntervalCategoryDataset createDataset() {
        
        final TaskSeries s1 = new TaskSeries("Proyecto");
        
        BDAdmin ver = new BDAdmin("SELECT * FROM PROYECTO");
        ResultSet rs = ver.consulta();
        
        boolean x = true;
        String actividad;
        Date fechaini;
        Date fechafin;
        String nombre;
        try {	
         if (rs.next()){
          while (x){     
            fechaini = rs.getDate("FECHA_INICIO");
            fechafin = rs.getDate("FECHA_FIN");
            nombre = rs.getString("NOMBRE");
            actividad = rs.getString("ACTIVIDAD");
            
            String year1= fechaini.toString();
            year1 = year1.substring(0,4);
            int anio1 = Integer.parseInt(year1);
            
            String month1= fechaini.toString();
            month1 = month1.substring(5,7);
            int mes1 = Integer.parseInt(month1)-1;
            
            String day1= fechaini.toString();
            day1 = day1.substring(8,10);
            int dia1 = Integer.parseInt(day1);
            
            String year2= fechafin.toString();
            year2 = year2.substring(0,4);
            int anio2 = Integer.parseInt(year2);
            
            String month2= fechafin.toString();
            month2 = month2.substring(5,7);
            int mes2 = Integer.parseInt(month2)-1;
            
            String day2= fechafin.toString();
            day2 = day2.substring(8,10);
            int dia2 = Integer.parseInt(day2);
            
            s1.add(new Task(actividad,
               new SimpleTimePeriod(date(dia1, mes1, anio1),
                                    date(dia2, mes2, anio2))));
               x = rs.next();
              }               
             }
            }
	     catch (Exception e) {
	     e.printStackTrace();
            }
        
         ver.cerrar();
        final TaskSeriesCollection collection = new TaskSeriesCollection();
        collection.add(s1);
       
        return collection;
    }
    
    private static Date date(final int dia, final int mes, final int anio) {
        final Calendar calendar = Calendar.getInstance();
        calendar.set(anio, mes, dia);
        final Date result = calendar.getTime();
        return result;
    }

    /**
     * Se crea una pizarra
     */
    private JFreeChart createChart(final IntervalCategoryDataset dataset) {
        final JFreeChart chart = ChartFactory.createGanttChart(
            "                            Cronograma",  // titulo
            "Actividades", // label de dominio
            "        Fecha", // label de rango
            dataset,             
            true,  // leyenda
            true,  // tooltips
            false  // urls
        );
        return chart;    
   }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(Diagrama.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarActionPerformed(evt);
            }
        });

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminarActionPerformed(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarActionPerformed(evt);
            }
        });

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(401, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addContainerGap(311, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarActionPerformed
  DiagramaAgregar agregar = new DiagramaAgregar(this.equipo, this);
  agregar.setVisible(true);
}//GEN-LAST:event_agregarActionPerformed

private void eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarActionPerformed
  DiagramaEliminar eliminar = new DiagramaEliminar(this.equipo, this);
  eliminar.setVisible(true);
}//GEN-LAST:event_eliminarActionPerformed

private void modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarActionPerformed
  DiagramaModificar modificar = new DiagramaModificar(this.equipo, this);
  modificar.setVisible(true);
}//GEN-LAST:event_modificarActionPerformed

private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
  this.setVisible(false);
}//GEN-LAST:event_cancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Diagrama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Diagrama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Diagrama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Diagrama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Diagrama dialog = new Diagrama("Cronograma", equipo);
                dialog.pack();
                RefineryUtilities.centerFrameOnScreen(dialog);
                dialog.setVisible(true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    // End of variables declaration//GEN-END:variables
}
